# -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
#    $Id$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from osv import osv, fields
import time

class stock_move(osv.osv):
    _inherit = 'stock.move'
    _columns = {
        'purchase_line_id': fields.many2one('purchase.order.line',
            'Purchase Order Line', ondelete='set null', select=True),
    }
    _defaults = {
        'purchase_line_id': lambda *a:False
    }
stock_move()

#
# Inherit of picking to add the link to the PO
#
class stock_picking(osv.osv):
    _inherit = 'stock.picking'
    
    def _set_minimum_date(self, cr, uid, ids, name, value, arg, context):
        if not value:
            return False
        if isinstance(ids, (int, long)):
            ids = [ids]
        for pick in self.browse(cr, uid, ids, context):
            sql_str = """update stock_move set
                    date_planned='%s'
                where
                    picking_id=%s """ % (value, pick.id)
            if pick.min_date:
                sql_str += " and (date_planned='" + pick.min_date + "' or date_planned<'" + value + "')"
            cr.execute(sql_str)
        return True
    
    def get_min_max_date(self, cr, uid, ids, field_name, arg, context={}):
        res = {}
        for id in ids:
            res[id] = {'min_date': False, 'max_date': False}
        if not ids:
            return res
        cr.execute("""select
                picking_id,
                min(date_planned),
                max(date_planned)
            from
                stock_move
            where
                picking_id in (""" + ','.join(map(str, ids)) + """)
            group by
                picking_id""")
        for pick, dt1, dt2 in cr.fetchall():
            res[pick]['min_date'] = dt1
            res[pick]['max_date'] = dt2
        return res
    
    _columns = {
        'state': fields.selection([
            ('draft', 'Draft'),
            ('auto', 'Waiting'),
            ('confirmed', 'Confirmed'),
            ('assigned', 'Available'),
            ('done', 'Done'),
            ('cancel', 'Canceled'),
            ], 'Status', readonly=True),
        'check_payment':fields.many2one('kdvn.request.of.payment','ROP'),                
        'received_date':fields.date('Received Date',states={'done':[('readonly',True)]}),
        'location_dest_id': fields.many2one('stock.location', 'Dest. Location', select=True),
        'location_id': fields.many2one('stock.location', 'Source Location', select=True),
        'address_id': fields.many2one('res.partner.address', 'Partner',states={'done':[('readonly',True)]}),
        'name': fields.char('Reference', size=64, select=True,states={'done':[('readonly',True)]}),
        'origin': fields.char('Origin Reference', size=64,states={'done':[('readonly',True)]}),
        'purchase_id': fields.many2one('purchase.order', 'Purchase Order',
            ondelete='set null', select=True,states={'done':[('readonly',True)]}),
        'min_date': fields.function(get_min_max_date, fnct_inv=_set_minimum_date, multi="min_max_date",
                 method=True, store=True, type='datetime', string='Planned Date'),
        'invoice_state': fields.selection([
            ("invoiced", "Invoiced"),
            ("2binvoiced", "To Be Invoiced"),
            ("none", "Not from Packing")], "Invoice Status",required=True, readonly=True, states={'draft': [('readonly', False)]}),                 
    }
    _defaults = {
        'purchase_id': lambda *a: False,
        'received_date':lambda *a: time.strftime("%Y-%m-%d"),
    }
    
    
    def _onchange_po(self,cr,uid,ids,po_id):
        p_id = False
        if po_id:
            part_id = self.pool.get('purchase.order').read(cr,uid,po_id,['partner_address_id'])
            if part_id:
                p_id = part_id['partner_address_id'][0]
        result={'value':{'address_id':p_id}}
        return result
    
    def kdvn_product_received(self,cr, uid, ids, *args):
        for pck in self.browse(cr,uid,ids):
            check_update = False
            for pck_move in pck.move_lines:
                pol_id = pck_move.purchase_line_id.id
                received_qty = pck_move.product_qty
                #,\price_subtotal2=price_unit*(product_qty+%d)- price_unit*(product_qty+%d)*discount_percent/100.0\
                cr.execute("Update \
                                    purchase_order_line \
                            set \
                            product_qty=product_qty+%d\
                            where id=%d" % (received_qty,pol_id))
#                check_update=True
#            if check_update:
#                cr.execute("Update \
#                                purchase_order\
#                            set\
#                                line_update=True,\
#                                amount_untaxed=(Select \
#                                                sum(price_unit*case when coalesce(product_qty,0)=0 then plan_qty else product_qty end) as untaxed_amount_before_discount\
#                                            from \
#                                                purchase_order_line where order_id=%d),\
#                                discount =(Select \
#                                                sum(price_unit*case when coalesce(product_qty,0)=0 then plan_qty else product_qty end)-sum(price_subtotal2) as discount\
#                                            from \
#                                                purchase_order_line where order_id=%d),\
#                                discount_percent=(Select \
#                                                case when sum(price_unit*case when coalesce(product_qty,0)=0 then plan_qty else product_qty end)=0 then 0 else (sum(price_unit*case when coalesce(product_qty,0)=0 then plan_qty else product_qty end)-sum(price_subtotal2))/sum(price_unit*case when coalesce(product_qty,0)=0 then plan_qty else product_qty end)*100.0 end as discount_percent\
#                                            from \
#                                                purchase_order_line where order_id=%d)\
#                            where id=%d" % (pck.purchase_id.id,pck.purchase_id.id,pck.purchase_id.id,pck.purchase_id.id))
            self.write(cr,uid,ids,{'state':'done'})
        return True
    
    def get_currency_id(self, cursor, user, picking):
        if picking.purchase_id:
            return picking.purchase_id.pricelist_id.currency_id.id
        else:
            return super(stock_picking, self).get_currency_id(cursor, user, picking)

    def _get_comment_invoice(self, cursor, user, picking):
        if picking.purchase_id and picking.purchase_id.notes:
            if picking.note:
                return picking.note + '\n' + picking.purchase_id.notes
            else:
                return picking.purchase_id.notes
        return super(stock_picking, self)._get_comment_invoice(cursor, user,
                picking)

    def _get_price_unit_invoice(self, cursor, user, move_line, type):
        if move_line.purchase_line_id:
            return move_line.purchase_line_id.price_unit
        return super(stock_picking, self)._get_price_unit_invoice(cursor,
                user, move_line, type)

    def _get_discount_invoice(self, cursor, user, move_line):
        if move_line.purchase_line_id:
            return 0.0
        return super(stock_picking, self)._get_discount_invoice(cursor, user,
                move_line)

    def _get_taxes_invoice(self, cursor, user, move_line, type):
        if move_line.purchase_line_id:
            return [x.id for x in move_line.purchase_line_id.taxes_id]
        return super(stock_picking, self)._get_taxes_invoice(cursor, user,
                move_line, type)

    def _get_account_analytic_invoice(self, cursor, user, picking, move_line):
        if move_line.purchase_line_id:
            return move_line.purchase_line_id.account_analytic_id.id
        return super(stock_picking, self)._get_account_analytic_invoice(cursor,
                user, picking, move_line)

    def _invoice_line_hook(self, cursor, user, move_line, invoice_line_id):
        return super(stock_picking, self)._invoice_line_hook(cursor, user,
                move_line, invoice_line_id)

    def _invoice_hook(self, cursor, user, picking, invoice_id):
        purchase_obj = self.pool.get('purchase.order')
        if picking.purchase_id:
            purchase_obj.write(cursor, user, [picking.purchase_id.id], {'invoice_id': invoice_id,
                })
        return super(stock_picking, self)._invoice_hook(cursor, user,
                picking, invoice_id)

stock_picking()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

